<?php

namespace App\Listeners;

use App\Events\ExampleEvent;
use App\Events\OrderSuccessEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use App\Internals\CourseInternal;
use App\Internals\StudyInternal;
use App\Jobs\CourseStartJob;

class WechatPushCourseStartListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ExampleEvent  $event
     * @return void
     */
    public function handle(OrderSuccessEvent $event)
    {
        Log::info('WechatPushCourseStartListener');
        $order = $event->order;
        $courses = $event->courses;

        // 触发该事件前，订单的课程已同步到study_api库中的user_course表中
        // 所以这里获得客户当前正在学习的课程，结果一定会有，不是之前购买的课程，就是本次购买的课程
        $courseCur = StudyInternal::getCurrentCourse($order->getUserId());

        Log::info('course:' . json_encode($courseCur));

        // 如果不是本次购买的课程，直接返回。
        if (! in_array($courseCur['courseId'], array_pluck($courses, 'courseId'))) {
            return;
        }

        // 获取课程信息
        $courseInfo = CourseInternal::getCourseByCourseId($courseCur['courseId']);
        Log::info('course:' . json_encode($courseInfo));
        if (! $courseInfo) {
            return;
        }

        dispatch(new CourseStartJob(
            $order->getUserId(),
            $courseInfo['level'],
            $this->pushDate(),
            $courseInfo['seriesName']
        ));

        Log::info('WechatPushCourseStartListener CourseStartJob');
    }

    public function pushDate()
    {
        $pushConf = config('lesson_push.push_date');
        $curWeekday = date('N');//1（表示星期一）到 7（表示星期天）

        foreach ($pushConf as $k=>$v) {
            if ($curWeekday < $v['weekday']) {
                return date('Y-m-d', strtotime('+' . ($v['weekday']-$curWeekday) . ' days', time())) . ' ' . $v['time'];
            }

            if ($curWeekday == $v['weekday']) {
                if (date('H:i') < $v['time']) {
                    return date('Y-m-d') . ' ' . $v['time'];
                }

                if (isset($pushConf[$k+1])) {
                    return date('Y-m-d', strtotime('+' . ($pushConf[$k+1]['weekday'] - $curWeekday) . ' days', time())) . ' ' . $pushConf[$k+1]['time'];
                } else {
                    return date('Y-m-d', strtotime('+' . (7 - $curWeekday + $pushConf[0]['weekday']) . ' days', time())) . ' ' . $pushConf[0]['time'];
                }
            }

            if (isset($pushConf[$k+1])) continue;

            return date('Y-m-d', strtotime('+' . (7 - $curWeekday + $pushConf[0]['weekday']) . ' days', time())) . ' ' . $pushConf[0]['time'];
        }
    }
}
